import { createStyles, Theme, withStyles } from "@material-ui/core/styles";
import { WithStyles } from "@material-ui/core/styles/withStyles";
import {
  Avatar,
  Button,
  Col,
  Divider,
  Form,
  Input,
  message,
  Row,
  Select,
  Upload
} from "antd";
import { FormComponentProps } from "antd/es/form";
import * as React from "react";
import doctorImage from "../../images/doctor_bg.png";
import { userData } from "../../type/UserInfoData";
import { getAddressData, getUserInfo } from "../../axios/RequestUser";
import { SelectValue } from "antd/lib/select";
import { UploadChangeParam } from "antd/lib/upload";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { login } from "../../redux/action/Actions";
import service from "../../axios/Service";
import * as qs from "qs";

const styles = (theme: Theme) =>
  createStyles({
    root: {},
    headImage: {
      display: "flex",
      justifyContent: "center",
      flexDirection: "column",
      alignItems: "center"
    },
    oneArea: {
      minHeight: 750
    },
    title: {
      fontWeight: "bold",
      fontSize: "16px"
    }
  });

interface Iprops extends WithStyles<typeof styles>, FormComponentProps {
  user: userData;
  login: () => void;
}
interface Istates {
  Province: addressOne[];
  city: addressOne[];
  Country: addressOne[];
  url: string;
}
interface addressOne {
  Code: string;
  Name: string;
  level: addressOne[];
}
/**
 * 账户设置
 */
class AccountSetting extends React.Component<Iprops, Istates> {
  private addressData: addressOne[] = [];
  private city: addressOne[] = [];
  constructor(props: Iprops) {
    super(props);
    this.state = {
      city: [],
      Country: [],
      Province: [],
      url: doctorImage
    };
  }
  public beforeUpload = (file: any) => {
    const isPNG =
      file.type === "image/png" ||
      file.type === "image/jpeg" ||
      file.type === "image/gif";
    if (!isPNG) {
      message.error("仅支持 JPG、PNG、gif 格式的文件!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片不得大于 2MB!");
    }
    return isPNG && isLt2M;
  };
  public updateUserInfo = () => {
    this.props.form.validateFields(() => {
      const data = Object.assign(
        this.props.user,
        this.props.form.getFieldsValue()
      );
      service.post("/user/modifyAccountInfo", data).then(value => {
        message.success("更新成功");
        this.getData();
      });
    });
  };
  public updatePassword = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        service
          .post(
            "/user/modifyPassword",
            qs.stringify(this.props.form.getFieldsValue())
          )
          .then(value => {
            if (value) {
              message.success("密码更新成功");
            }
          });
      }
    });
  };
  public componentWillMount(): void {
    getAddressData().then(value => {
      this.addressData = value.data;
      this.setState({
        Province: value.data
      });
      if (this.props.user.addressProvince && this.props.user.addressCity) {
        this.getAddressCity(this.props.user.addressProvince);
        this.getAddressCountry(this.props.user.addressCity);
      }
    });
  }
  /**
   * 获取用户信息
   */
  public getData = () => {
    getUserInfo().then(value => {
      window.localStorage.setItem("userData", JSON.stringify(value.data));
      this.props.login();
    });
  };
  public handleChange = (file: UploadChangeParam) => {
    if (file.file.response) {
      message.success("头像更换成功");
      this.getData();
    }
  };
  /**
   *  获取城市名称
   */
  public getAddressCity = (value: SelectValue, clear?: boolean) => {
    if (clear) {
      this.props.form.setFieldsValue({
        addressCity: "",
        addressCountry: ""
      });
    }
    const address = this.addressData.filter(value1 => {
      return value1.Code === value;
    });
    this.city = address[0].level;
    this.setState({
      city: address[0].level,
      Country: []
    });
  };
  /**
   * 获取镇的名称
   */
  public getAddressCountry = (value: SelectValue, clear?: boolean) => {
    if (clear) {
      this.props.form.setFieldsValue({
        addressCountry: ""
      });
      this.setState({
        Country: []
      });
    }
    const address: addressOne[] = this.city.filter(value1 => {
      return value1.Code === value;
    });
    this.setState({
      Country: address[0].level
    });
  };
  public compareToFirstPassword = (rule: any, value: string, callback: any) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue("newPwd")) {
      callback("两次密码不一致");
    } else {
      callback();
    }
  };
  public render() {
    const { classes } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { user } = this.props;
    return (
      <div className={classes.oneArea}>
        <div>
          <Row>
            <Col span={4} className={classes.title}>
              用户头像
            </Col>
            <Col span={16} className={classes.headImage}>
              <Avatar src={user.avatarUrl} size={120} />
              <Upload
                action={"/user/uploadAvatar"}
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
                showUploadList={false}
              >
                <a>更换头像</a>
              </Upload>
            </Col>
          </Row>
        </div>
        <Divider />
        <div>
          <Row>
            <Col span={3} className={classes.title}>
              基本信息
            </Col>
            <Col span={16}>
              <Form style={{ paddingTop: "40px" }}>
                <Form.Item
                  label={"电子邮箱"}
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 6 }}
                >
                  {getFieldDecorator("email", { initialValue: user.email })(
                    <Input />
                  )}
                </Form.Item>
                <Form.Item
                  label={"家庭地址"}
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator("addressProvince", {
                    initialValue: user.addressProvince
                  })(
                    <Select
                      style={{ width: "33%" }}
                      showSearch={true}
                      placeholder={"省"}
                      onChange={value => {
                        this.getAddressCity(value, true);
                      }}
                    >
                      {this.state.Province.map((value: any, index, array) => {
                        return (
                          <Select.Option value={value.Code} key={value.Code}>
                            {value.Name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  )}
                  {getFieldDecorator("addressCity", {
                    initialValue: user.addressCity
                  })(
                    <Select
                      style={{ width: "33%" }}
                      showSearch={true}
                      placeholder={"市"}
                      onChange={value => {
                        this.getAddressCountry(value, true);
                      }}
                    >
                      {this.state.city.map((value: any, index, array) => {
                        return (
                          <Select.Option value={value.Code} key={value.Code}>
                            {value.Name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  )}
                  {getFieldDecorator("addressCountry", {
                    initialValue: user.addressCountry
                  })(
                    <Select
                      style={{ width: "33%" }}
                      showSearch={true}
                      placeholder={"县"}
                    >
                      {this.state.Country.map((value: any, index, array) => {
                        return (
                          <Select.Option value={value.Code} key={value.Code}>
                            {value.Name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label={"详细地址"}
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator("addressArea", {
                    initialValue: user.addressArea
                  })(<Input />)}
                  <Button onClick={this.updateUserInfo} type={"primary"}>
                    保存基本信息
                  </Button>
                </Form.Item>
              </Form>
            </Col>
          </Row>
        </div>
        <Divider />
        <div>
          <Col span={3} className={classes.title}>
            账户信息
          </Col>
          <Col span={16}>
            <Form style={{ paddingTop: "40px" }}>
              <Form.Item
                label={"旧密码"}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 6 }}
              >
                {getFieldDecorator("oldPwd")(<Input type={"password"} />)}
              </Form.Item>
              <Form.Item
                label={"新密码"}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 6 }}
              >
                {getFieldDecorator("newPwd")(<Input type={"password"} />)}
              </Form.Item>
              <Form.Item
                label={"确认密码"}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 6 }}
              >
                {getFieldDecorator("confirmPwd", {
                  rules: [{ validator: this.compareToFirstPassword }]
                })(<Input type={"password"} />)}
                <Button onClick={this.updatePassword} type={"primary"}>
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state: any) => {
  return {
    user: state
      .get("loginOrLogoutReducer")
      .get("user")
      .toJS()
  };
};
const mapDispatchToProps = ({} = (dispatch: any, ownProps: any) => {
  return bindActionCreators(
    {
      login
    },
    dispatch
  );
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create()(withStyles(styles)(AccountSetting)));
